// 防抖函数实现
import { gsap } from 'gsap'
export function debounce(func: Function, delay: number) {
  let timeoutId: any = null

  return function (this: any, ...args: any[]) {
    const context = this

    clearTimeout(timeoutId)

    timeoutId = setTimeout(() => {
      func.apply(context, args)
    }, delay)
  }
}

// 滑动到底部的动画实现
export const handleMoveToBottom = (element: HTMLDivElement) => {
  if (element) {
    gsap.to(element, {
      scrollTop: element.scrollHeight,
      duration: 1,
      ease: 'power2.out'
    })
  }
}

export const isElementToBottom = (element: HTMLDivElement) => {
  if (element) {
    return element.scrollTop + element.clientHeight + 1 <= element.scrollHeight
  } else {
    return false
  }
}

// 提取markdown文本中的代码
export function extractCodeBlocks(markdownText: string): string {
  const codeBlocks = []

  // 正则表达式匹配代码块
  const codeBlockRegex = /```[^\n]*\n([\s\S]*?)```/g

  let match
  while ((match = codeBlockRegex.exec(markdownText)) !== null) {
    // 提取代码块内容
    const codeBlock = match[1].trim()
    codeBlocks.push(codeBlock)
  }

  return codeBlocks.join('\n')
}

function decodeUnicode(str: string) {
  return str.replace(/\\u([0-9A-Fa-f]{4})/g, function (match, p1) {
    return String.fromCharCode(parseInt(p1, 16))
  })
}
// 解析流式数据的content
export function parseContent(input:string) {
  input = decodeUnicode(input)
  const regex_object = /({.*?})(?=\s*{|$)/g
  let match

  const result = {
    chat_id: 0,
    content: ''
  }
  while ((match = regex_object.exec(input)) !== null) {
    try {
      const obj = JSON.parse(match[1])
      result.chat_id = obj.chat_id
      result.content += obj.content
    } catch (error) {
      console.error('Invalid JSON object:', match[1], error)
    }
  }

  return result
}